package com.example.demo.web;

import com.example.demo.common.ResponseResult;
import com.example.demo.common.ResponseResultFactory;
import com.example.demo.service.FileService;
import com.example.demo.service.impl.FileServiceImpl;
import com.example.demo.utils.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created by lyc on 2019/6/7.
 * 文件操作
 *
 * js 思路
 * https://www.cnblogs.com/xyzhanjiang/p/11887109.html
 */
@Controller
@Slf4j
@RequestMapping
public class FileAction {

    /**
     * tip 小知识这里其实有多套（本地 阿里 七牛） 实现
     * 可以根据 传参不同 从容器 取对于的实现 然后管理不同的 文件服务器
     * 联想策略模式 消除 if else
     */
    //@Autowired
    private FileService fileService = (FileServiceImpl) SpringUtils.getBean("fileServiceImpl");

    @GetMapping
    public String index() {
        return "index";
    }

    /**
     * 单文件
     * @param file
     * @param request
     * @return
     */
    @PostMapping("/uploads/upload1")
    @ResponseBody
    public ResponseResult upload1(@RequestParam("file") MultipartFile file, HttpServletRequest request) {

        String result = null;
        try {
            result = fileService.upload(file,request);
        } catch (IOException e) {
            ResponseResultFactory.fieldFail("上传失败",result);
        }
        return ResponseResultFactory.success("上传成功",result);
    }

    /**
     * 多文件
     * @param files
     * @return
     * @throws IOException
     */
    @PostMapping("/uploads/upload2")
    @ResponseBody
    public ResponseResult upload2(@RequestParam("file") MultipartFile[] files) {
        String result = null;
        try {
            result = fileService.uploads(files);
        } catch (IOException e) {
            ResponseResultFactory.fieldFail("上传失败",result);
        }
        return ResponseResultFactory.success("上传成功",result);
    }

    /**
     * base64
     * @param base64Image
     * @return
     * @throws IOException
     */
    @PostMapping("/uploads/upload3")
    @ResponseBody
    public ResponseResult upload2(String base64Image)  {
        String result = null;
        try {
            result = fileService.uploadBase64(base64Image);
        } catch (IOException e) {
            ResponseResultFactory.fieldFail("上传失败",result);
        }
        return ResponseResultFactory.success("上传成功",result);
    }
}
